var baseUrl = "http://www.ziselu.com/zslapi/";
var imgBaseUrl = "http://www.ziselu.com/zsl/file/";
var Token = localStorage.getItem("Token");
var phone_rexg = /^1\d{10}$/;
var layer;
//不需要登录的页面
var noNeedLogin = ['product_detail','index','product_list','Submission','register_01','register_02','register_03',"store","login","set_pswd_succ","forget_password","activity","head_01","head_search"];

(noNeedLogin.indexOf(pageName(window.location.href)) == -1 && !Token)?location.href = "http://www.ziselu.com/car/page/login.html":"";

//获取当前登录人店铺id
if(!localStorage.getItem("storeId")){
    ajax_async("/web/auth/info",{},function (data) {
        localStorage.setItem("storeId",data.storeId)
    })
}

document.title = "紫色鹭汽配网";
$(document.head).append('<link rel="icon" href="../img/login-sty1.png" type="image/x-icon"/>')

$("body").on("click", ".icon_checkbox", function () {
    $(this).toggleClass("active");
});
$("body").on("click", ".tabRight .icon_top_white", function () {
    $("html,body").animate({scrollTop: 0}, 500);
});

layui.use(['layer'], function () {
    layer = layui.layer;
})

$(document).on('click','.signBtn',function(){
    location.href = "register_01.html"
})

$(document).on('click','.go-authentication',function(){
    var state = localStorage.getItem('state');
    var url = "http://www.ziselu.com/car/page/";
    if(!hasToken()){return}
    get_ajax("/sys/authentication/myAuthentication", {}, function (data) {
        if(!data){
            window.open(url+'Submission.html')
        }else{
            if(state==1 || state==3){
                window.open(url+'submission_state.html?state='+state)
            }else if(state==2){
                window.open(url+'store_enterprise.html');
            }
        }
    })
})
function goIndex() {
    location.href = "index.html"
}

//网址参数获取
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return null;
}

// ajax封装
function get_ajax(url,sendData,rebackFun) {
    if(localStorage.getItem("Token")){
        sendData["Token"] = localStorage.getItem("Token");
    }
    $.post(baseUrl+url,sendData,function (data) {
        if(data.code != 0){
            layer.msg(data.msg)
            return
        }else{
            var data = data.data;
            rebackFun(data);
        }
    })
}
function get_ajaxPage(url,sendData,rebackFun) {
    if(localStorage.getItem("Token")){
        sendData["Token"] = localStorage.getItem("Token");
    }
    $.post(baseUrl+url,sendData,function (data) {
        if(data.code != 0){
            layer.msg(data.msg)
            return
        }else{
            var data = data;
            rebackFun(data);
        }
    })
}


function ajax_async(url,sendData,rebackFun) {
    if(localStorage.getItem("Token")){
        sendData["Token"] = localStorage.getItem("Token");
    }
    $.ajax({
        url: baseUrl+url,
        data:sendData,
        async:false,
        type:'POST',
        success:function (data) {
            if(data.code != 0){
                layer.msg(data.msg);

            }else{
                var data = data.data;
                rebackFun(data);
            }
        }
    })
}

//循环存储
function setStorage(obj) {
    for (var index in obj){
        localStorage.setItem(index,obj[index]);
    }
}




//地址三级联动
function initAreaSelect() {
    ajax_async("/web/auth/getAreaList",{},function (data) {
        var str;
        data.forEach(function (item) {
            str += '<option value="'+item.id+'">'+item.name+'</option>';
        })
        $("#province").append(str);
    });

    $("body").on("change","#province",function () {
        var id = $(this).val();
        ajax_async("/web/auth/getListByPid",{id:id},function (data) {
            var str="";
            data.forEach(function (item) {
                str += '<option value="'+item.id+'">'+item.name+'</option>';
            })
            $("#city").html(str);
            var cityId = $("#city").val()?$("#city").val():$("#city option:first-child").val();
            ajax_async("/web/auth/getListByPid",{id:cityId},function (data) {
                var str="";
                data.forEach(function (item) {
                    str += '<option value="'+item.id+'">'+item.name+'</option>';
                })
                $("#area").html(str);
                layui.use(['form'], function () {
                    var form = layui.form;
                    form.render();
                })
            });
        });
    })

    $("body").on("change","#city",function () {
        var id = $(this).val();
        ajax_async("/web/auth/getListByPid",{id:id},function (data) {
            var str="";
            data.forEach(function (item) {
                str += '<option value="'+item.id+'">'+item.name+'</option>';
            })
            $("#area").html(str);
        });
    })
}
layui.use(['layer', 'form'], function(){
    var layer = layui.layer
        ,form = layui.form;
    form.on('select(province)', function(data){
        $("#province").change();
        form.render('select')
    });
    form.on('select(city)', function(data){
        $("#city").change();
        form.render('select')
    });
});

//地址选择三级回显
function initLayuiArea(provinceId,cityId,districtId) {
    $("#province").val(provinceId).trigger("change");
    $("#city").val(cityId).trigger("change");
    $("#area").val(districtId);
    layui.use(['layer', 'form'], function(){
        var layer = layui.layer
            ,form = layui.form;
        form.render('select')
    });
}

/*------------tree.start------------*/
var company;
/*取出所有的单位*/
function getAllClass() {
    get_ajax('/sys/storeCommodityType/getAllListTree',{},function (data) {
        $('#classBox').empty();
        company = data;
        var setting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onCheck: zTreeOnCheck
            }
        };
        var zNodes = company;
        $.fn.zTree.init($("#classBox"), setting, zNodes);
    })
}


function getChoiceClass() {
    var treeArr = [];
    var treeObj = $.fn.zTree.getZTreeObj("classBox");
    var nodes = treeObj.getCheckedNodes(true);
    for (var i = 0; i < nodes.length; i++) {
        treeArr.push(nodes[i].id); //获取选中节点的值
    }
    return treeArr;
}

$('body').on("click","#proClass",function () {
    $('#classBox').show();
});
$("body").click(function () {
    $("#classBox").hide();
})
$('body').on("click","#classBox,#proClass",function () {
    return false;
});
function zTreeOnCheck(event, treeId, treeNode) {
    var nval = "";
    var treeObj = $.fn.zTree.getZTreeObj("classBox");
    var nodes = treeObj.getCheckedNodes(true);
    for (var i = 0; i < nodes.length; i++) {
        nval += nodes[i].name + ",";
    }
    $('#proClass').val(nval.substr(0, nval.length - 1));
};
/*------------tree.end------------*/

function get_confirm(msg,rebackFun) {
    var msg = msg;
    if(typeof(msg) == "function"){
        rebackFun = msg;
        msg = '提交成功!';
    }
    if(!msg){
        msg = '提交成功!'
    }
    layer.confirm(msg, {
            btn: ['确定', '取消']
        }, function (index) {
            layer.close(index);
            if(rebackFun){
                rebackFun();
            }

        }
    );
}

$('body').on("click",".computed .icon_plus",function () {
    var value = $(this).prev().val();
    $(this).prev().val(Number(value)+1)
});
$('body').on("click",".computed .icon_minus",function () {
    var value = $(this).next().val();
    if(value > 1){
        $(this).next().val(Number(value)-1)
    }
});

//点击需要登录权限
function hasToken(){
    if(!Token){
        layer.msg('请您先登录');
        return false;
    }else{
        return true
    }
}

$(document).on('click','.go-shopcard,.search_head .my_shopcar',function(){
    hasToken()?window.open('shop_car.html'):'';
})
$(document).on('click','.go-myorder',function(){
    hasToken()?window.open('my_order.html'):'';
})
$(document).on('click','.go-myhas,.go-store',function(){
    hasToken()?window.open('collect_store.html'):'';
})
$(document).on('click','.go-record',function(){
    hasToken()?window.open('history.html'):'';
})
$(document).on('click','.ruzhu',function(){
    layer.msg('请先登录或注册！');
})
$(document).on('click','.go-shop',function(){
    hasToken()?window.open('shop_car.html'):'';
})
//提示入驻
function openShop(){
    if(localStorage.getItem("type") == 1){
        layer.msg('请完成企业认证！');
    }
}


//更新购物车数量
updataCardNum()
function updataCardNum(){
    var numTotal = 0;
    if(Token){
        get_ajax("/sys/car/getCarList", {}, function (data) {
            var carList= data;
            for(var i = 0;i<carList.length;i++){
                for(var k = 0;k<carList[i].list.length;k++){
                    numTotal += 1;
                }
            }
            $('.car-num,.car_num').html(numTotal);
        })
    }else {
        $('.car-num,.car_num').html(0);
    }


};


//我的店铺跳转权限

$(document).on('click','.store_tab .store-info',function () {  //
    window.location.href='store_info.html';
})
$(document).on('click','.store_tab .banner-admmin',function () {  //调轮播管理
    if(localStorage.getItem("type") == 1){
        layer.msg('请完成企业认证！');
    }else{
        window.location.href='store_banner.html';
    }

})


$(document).on('click','.store_tab .product-admin',function () {  //
    if(localStorage.getItem('storeId')){
        window.location.href='store_product.html';
    }else{
        layer.msg('请填写基本信息')
    }

})
$(document).on('click','.store_tab .order-admin',function () {  //
    if(localStorage.getItem('storeId')){
        window.location.href='store_manage.html';
    }else{
        layer.msg('请填写基本信息')
    }

})
$(document).on('click','.store_tab .evaluate-admin',function () {  //
    if(localStorage.getItem('storeId')){
        window.location.href='store_evaluate.html';
    }else{
        layer.msg('请填写基本信息')
    }

})





function pageName(a) {
    var b = a.split("/");
    var c = b.slice(b.length - 1, b.length).toString(String).split(".").slice(0, 1)[0];
    return c;
}





$(document).on('click','.store-enter',function(){
    var state = localStorage.getItem('state')
    if(!hasToken()){return}
    get_ajax("/sys/authentication/myAuthentication", {}, function (data) {
        if(!data){
            window.open('Submission.html')
        }else{
            if(state==1 || state==3){
                window.open('submission_state.html?state='+state)
            }else if(state==2){
                location.href = 'store_enterprise.html';
            }
        }
    })



})



function initForm() {
    layui.use(['form'], function () {
        var form = layui.form;
        form.render();
    })
}


//前台管理系统
setTimeout(function(){
    if(Token){
        $('.login-0').hide();
        $('.login-name').html(localStorage.getItem('username'));
    }else{
        $('.login-1').show();
    }
},100)



$("body").on("click",".loginOut",function () {
    localStorage.removeItem("Token");
    localStorage.removeItem("userId");
    localStorage.removeItem("storeId");
    noNeedLogin.indexOf(pageName(window.location.href)) == -1?location.href = "login.html":location.reload()
})

$("body").on("click","#left_tab_html .left-box .li-sty",function () {
    var index = $(this).index();
    $(this).addClass("active").siblings().removeClass("active");
    $(".left-box .menu-s").eq(index).show().siblings(".menu-s").hide();
})


//统一返回
    function addNewBlack(){
        setTimeout(function(){
            window.history.go(-1);
        },1000)
    }








